package com.fowo.api.controller.purchase.interfaceImp;

import com.fowo.api.entity.DevelopmentTaskzb;
import com.fowo.api.model.development.task.DevelopmentTaskVo;
import com.fowo.api.model.development.taskzb.DevelopmentTaskzbItemVo;
import com.fowo.api.model.sourcing.manage.SourcingManageBatchCompletionAction;
import com.fowo.api.model.sourcing.manage.SourcingManageVo;
import com.fowo.api.service.DevelopmentTaskService;
import com.fowo.api.service.DevelopmentTaskzbService;
import com.fowo.api.service.impl.DevelopmentTaskServiceImpl;
import com.fowo.api.service.impl.DevelopmentTaskzbServiceImpl;
import com.fowo.api.service.impl.SourcingManageServiceImpl;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class sourcingManageBatchCompletion implements SourcingManageBatchCompletionAction {

    @Resource
    private SourcingManageServiceImpl sourcingManageService;
    @Resource
    private DevelopmentTaskServiceImpl developmentTaskService;

    @Resource
    protected DevelopmentTaskzbServiceImpl developmentTaskzbService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void run(List<Long> idList) throws Exception {
     for(int i=0;i<idList.size();i++){
      Long aLong = idList.get(i);
            handData(aLong);
      }
    }

    private void handData(Long aLong) throws Exception {
        SourcingManageVo voById = sourcingManageService.getVoById(aLong);
        Assert.isTrue(voById.getState().equals("0"),"违规操作");
        voById.setState("2");
        //设置子表数量
        DevelopmentTaskzb byId = developmentTaskzbService.getById(voById.getTaskItemId());
        byId.setCompletedQuantity(byId.getCompletedQuantity()!=null?byId.getCompletedQuantity()+1:1);
        developmentTaskzbService.updateById(byId);
        //判断主表的子表是否全部完成了
        DevelopmentTaskVo voById1 = developmentTaskService.getVoById(voById.getTaskId());
        List<DevelopmentTaskzbItemVo> zbId=voById1.getZbId();
        List<DevelopmentTaskzbItemVo> collect = zbId.stream().filter(s -> s.getCompletedQuantity() != null && s.getCompletedQuantity().intValue() >= s.getPlannedQuantity().intValue()).collect(Collectors.toList());
        if(zbId.size()==collect.size()){
            voById1.setState("3");
            developmentTaskService.update(voById1);
        }
        sourcingManageService.update(voById);
    }


}